C++进制转换(十进制转二进制、八进制、任意进制) 原作者写的很全面,很详细。

 

C++进制转换(十进制转二进制、八进制、任意进制)

分类: C++   1869人阅读  评论(0)  收藏  举报

十进制转二进制:

  1. //十进制转二进制  
  2. #include<iostream>  
  3. using namespace std;  
  4.   
  5. void printbinary(const unsigned int val)  
  6. {  
  7.     for(int i = 16; i >= 0; i--)  
  8.     {  
  9.         if(val & (1 << i))  
  10.             cout << "1";  
  11.         else  
  12.             cout << "0";  
  13.     }  
  14. }  
  15.   
  16. int main()  
  17. {  
  18.     printbinary(1024);  
  19.     return 0;  
  20. }  

十进制转八进制

  1. //十进制转八进制  
  2. #include <iostream>  
  3. #include <vector>  
  4. using namespace std;  
  5.   
  6. int main()  
  7. {  
  8.     cout<<"input a number:"<<endl;  
  9.     int d;  
  10.     vector<int> vec;  
  11.   
  12.     cin>>d;  
  13.     while (d)  
  14.     {  
  15.         vec.push_back(d%8);  
  16.         d=d/8;  
  17.     }  
  18.   
  19.     cout<<"the result is:"<<endl;  
  20.     for(vector<int>::iterator ip=vec.end()-1;ip>=vec.begin();)  
  21.     {  
  22.         cout<<*ip--;  
  23.     }  
  24.     cout<<endl;  
  25.       
  26.     return 0;  
  27. }  

十进制转任意进制:

  1. //十进制转换为任意进制的源码  
  2. #include <iostream>  
  3. using namespace std;  
  4.   
  5. int main()  
  6. {  
  7.     long n;  
  8.     int p,c,m=0,s[100];  
  9.     cout<<"输入要转换的数字:"<<endl;  
  10.     cin>>n;  
  11.     cout<<"输入要转换的进制:"<<endl;  
  12.     cin>>p;  
  13.   
  14.     cout<<"("<<n<<")10="<<"(";  
  15.   
  16.     while (n!=0)//数制转换,结果存入数组s[m]  
  17.     {  
  18.         c=n%p;  
  19.         n=n/p;  
  20.         m++;s[m]=c;   //将余数按顺序存入数组s[m]中  
  21.     }  
  22.   
  23.     for(int k=m;k>=1;k--)//输出转换后的序列  
  24.     {  
  25.         if(s[k]>=10) //若为十六进制等则输出相对应的字母  
  26.             cout<<(char)(s[k]+55);  
  27.         else         //否则直接输出数字  
  28.             cout<<s[k];  
  29.     }  
  30.   
  31.     cout<<")"<<p<<endl;  
  32.   
  33.     return 0;  
  34. }  

通过库函数实现八进制、十六进制输出:

  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. int main()  
  5. {  
  6.     int test=64;  
  7.     cout<<"DEC:"<<test<<endl;  
  8.     cout<<"OCT:"<<oct<<test<<endl;//八进制  
  9.     cout<<"HEX:"<<hex<<test<<endl;//十六进制  
  10.   
  11.     return 0;  
  12. }  
  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值